<template>
  <div>
    <!-- 历史交易查询 -->
    <!-- 查询结果提示 -->
    <div v-if="showWarning" style="margin-top: 10px; color: #FF4949; font-size: 14px; font-weight: normal; padding-left: 10px; background-color: #f8f8f8;">
      {{ $t('stm.cusTransHis.prompt') }}
    </div>
    <VxePage
      id="0001.A129.0010"
      ref="0001.A129.0010"
      :query-form="queryForm"
      :state-count-config="statusCountConfig"
        :validator="{
            validateDoubleProp
        }"
      :list-page-config="{
        tableFixColumns: true,
        tableFixHeight: true,
        tableMode: 'radio',
        showCfgButton: true
      }"
      opt-code="STM004GET1111"
      :his-columns="detailColumn1"
      @doDetail="doDetail"
      @doLocalClearingSysTranInfo="doLocalClearingSysTranInfo"
      @doExport="doExport"
      @doPrint="doPrint"
      @openDetailWidow="openDetailWidow"
    >
      <template #buttonGroup>
        <bfe-button
          type="primary"
          icon="search"
          :loading="$refs['0001.A129.C013'] ? $refs['0001.A129.C013'].tableLoading : false"
          @click="doSearch"
        >
          {{ $t('stm.btn.query') }}
        </bfe-button>
      </template>
      <!-- 银行名称 -->
      <template #cond_bankId="{cfg}">
        <bfe-form-item :label="$t('stm.cusTransHis.bankName')" style="width: 210px;" prop="bankId" :rules="cfg.rule">
          <bfe-select v-model="queryForm.bankId" size="small" :disabled="userInfo.userAhrInstNo!=='3'" :placeholder="$t('stm.validateTip.pleaseSelect')" filterable @change="getCertType">
            <bfe-option v-for="(item, index) in bankIdObj[language]" :key="item.key + index" :label="item.value" :value="item.key" />
          </bfe-select>
        </bfe-form-item>
      </template>

      <!-- 交易日期 -->
        <template #cond_transDate="scope">
            <bfe-form-item :label="scope.cfg.label" :prop="scope.cfg.prop" :rules="ruleTest">
                <bfe-date-picker v-model="queryForm[scope.cfg.prop]" :picker-options="pickerOptions"  type="daterange" size="small"  :editable="true"  :placeholder="$t('stm.validateTip.pleaseSelect')"  format ></bfe-date-picker>
            </bfe-form-item>
        </template>

      <!-- 交易主体客户号 -->
        <template #cond_acctNo="scope">
            <bfe-form-item :label="scope.cfg.label" :prop="scope.cfg.prop" :rules="ruleTestB">
                <bfe-input v-model="queryForm[scope.cfg.prop]"></bfe-input>
            </bfe-form-item>
        </template>

      <!-- 交易码 -->
      <template #cond_tranCode="{cfg}">
        <bfe-form-item :label="$t('stm.cusTransHis.tranCode')" style="width: 210px;" prop="tranCode">
          <bfe-input v-model="queryForm.tranCode" size="small" type="input" :placeholder="$t('stm.validateTip.pleaseInput')" @blur="getCusInfo" />
        </bfe-form-item>
      </template>

      <!-- 交易主体账号 -->
      <template #cond_cstId="scope">
        <bfe-form-item :label="scope.cfg.label" :prop="scope.cfg.prop" :rules="ruleTestA">
            <bfe-input v-model="queryForm[scope.cfg.prop]"></bfe-input>
        </bfe-form-item>
      </template>

      <template #cond_employeeFlag="{cfg}">
        <bfe-form-item :label="$t('stm.cusTransHis.employeeFlag')" style="width: 210px;">
          <bfe-checkbox v-model="employeeFlagChecked" disabled />
        </bfe-form-item>
      </template>
      <template #cond_vipCode="{cfg}">
        <bfe-form-item :label="$t('stm.cusTransHis.vipCode')" style="width: 210px;">
          <bfe-checkbox v-model="vipCodeChecked" disabled />
        </bfe-form-item>
      </template>
    </VxePage>
    <ColumnDialog ref="columnDialog" dialog-width="70%">
      <template #btnBefore>
        <bfe-button type="primary" icon="Print" @click="doDetailPrint">
          {{ $t('stm.cusTransHis.print') }}
        </bfe-button>
      </template> 
    </ColumnDialog>
    <ColumnDialog ref="columnDialogTwo" dialog-width="70%" />
  </div>
</template>

<script>
import VxePage from '@/components/vxePage/vxePage';
import ColumnDialog from '@stm/components/ColumnDialog';
import {detailColumn1,detailColumn} from './config';
import {localClearingSysTranInfoList} from './config';
import {mapState} from 'vuex';
import mixinList from '@stm/mixins'
export default {
  components: {
    VxePage,
    ColumnDialog
  },
  mixins: [mixinList],
  data(){
    return {
      showWarning: false,
      employeeFlagChecked: false,
      vipCodeChecked: false,
      queryForm: {
        bankId: '0'
      },
      statusCountConfig: {},
      detailColumn,
      detailColumn1,
      localClearingSysTranInfoList,
      optCode: 'STM004GET1101',
      needVild: false,
      bankIdObj: {
        zh_TW: [],
        en_US: []
      },
 pickerOptions: {
        onPick: ({ minDate, maxDate }) => {
            console.log(minDate, maxDate, '打印日期');
          // 当用户选择第一个时间后，记录这个时间，并触发 disabledDate 的更新
          this.minDate = minDate;
          this.maxDate = maxDate;
        },
        disabledDate: (time) => {
            console.log(this.minDate, this.maxDate, '打印日期');
            
          if (!this.minDate && !this.maxDate) {
            // 没有选择任何时间，可以自由选择
            return false;
          }

          // 如果已经选择了开始时间，则限制结束时间必须在 ±3 个月范围内
          if (this.minDate && !this.maxDate) {
            const earliest = new Date(this.minDate);
            earliest.setMonth(earliest.getMonth() - 3);

            const latest = new Date(this.minDate);
            latest.setMonth(latest.getMonth() + 3);

            return time < earliest || time > latest;
          }

          // 如果已经选择了结束时间，则限制开始时间必须在 ±3 个月范围内
          if (this.maxDate && !this.minDate) {
            const earliest = new Date(this.maxDate);
            earliest.setMonth(earliest.getMonth() - 3);

            const latest = new Date(this.maxDate);
            latest.setMonth(latest.getMonth() + 3);

            return time < earliest || time > latest;
          }

          // 如果两个都选了，就按正常逻辑处理（比如允许修改）
          return false;
        },
      },
      detailRowData: {},
        ruleTest: [
            {validator: this.validateDoubleProp, trigger: 'blur'}
        ],
        ruleTestA: [
            {validator: this.validateDoubleProp, trigger: 'blur'}
        ],
        ruleTestB: [
            {validator: this.validateDoubleProp, trigger: 'blur'}
        ]
    }
  },
  computed: {
    ...mapState({
      language: state => state.base.language || 'zh_TW',
      btnData:state => state.base.btnData
    }),
  },
  watch: {
    'queryForm.bankId'(newValue){
      if(newValue && String(newValue) === '148') {
        this.$message.error('以下條件請至少輸入一項,交易主體客戶號、交易主體賬號')
      }
    }
  },

  activated() {
   
    console.log(this.$route.params, 'this.$route.params');
    const { type, transDate,cstId,bankId } = this.$route.params;

    if (type === 'toDoSearch' ) {
      this.$set(this.queryForm, 'cstId', cstId);
      this.$set(this.queryForm, 'bankId', bankId);
      this.$set(this.queryForm, 'transDate', transDate);
      setTimeout(() => {
        this.doSearch();
      }, 200);
    }
    
  },
  mounted() {
    if(this.userInfo.userAhrInstNo !== '3') {
      this.queryForm.bankId = this.userInfo.userAhrInstNo;
    }
    this.getBankIdObj('bankIdObj', 'STM006PUBLIC0101');
    this.employeeFlagChecked= this.btnData.filter(item=>item.btnRefno==='0001.A129.0010.0006')[0]?true:false
    this.vipCodeChecked= this.btnData.filter(item=>item.btnRefno==='0001.A129.0010.0007')[0]?true:false
    console.log(this.btnData,this.employeeFlagArr,this.vipCodeArr)
    this.getCertType();
  },
  methods: {
    // 导出接口
    doExport() {
      if (!this.queryForm.bankId) {
        this.$message.warning(this.$t('stm.ruleMessage.bankId'));
        return false;
      }
      this.baseDownload(
        {
          optCode: 'STM004GET1105',
          payload: {
            ...this.queryForm,
            caseType: 'trade',
            caseId: '3',
            chooseType: '1',
            columnType: '2',
          },
        },
        this.$api['_01_STM004DOWNLOAD1200']
      );
    }, 
    doDetailPrint() {
      console.log(this.detailRowData)
      if (!this.detailRowData.bankid) {
        this.$message.warning(this.$t('stm.ruleMessage.bankId'));
        return false;
      }
      this.baseDownload(
        {
          optCode: 'STM004GET1113',
          payload: {
            seqNo: this.detailRowData.seqno,
            bankId: this.detailRowData.bankid,
            cstId: this.detailRowData.cstid,
          },
        },
        this.$api['_01_STM004DOWNLOAD1200']
      );
    },
    doPrint() {
      if (!this.queryForm.bankId) {
        this.$message.warning(this.$t('stm.ruleMessage.bankId'));
        return false;
      }
      this.baseDownload(
        {
          optCode: 'STM004GET1106',
          payload: {
            ...this.queryForm,
            caseType: 'trade',
            caseId: '3',
            chooseType: '1',
            columnType: '2',
          },
          pageInfo: {...this.$refs['0001.A129.0010'].pagination}
        },
        this.$api['_01_STM004DOWNLOAD1200']
      );
    },
    openDetailWidow() {},
    getCertType(){
      this.selectObj = {
        certType: {},
      }
      const arr = [
        {paratype: 'certType', paraname: this.queryForm.bankId || '0'},
      ]
    if(this.queryForm.bankId) {
        const params = {
            optCode: 'STM002GET1304',
            payload: {
              bankId: this.queryForm.bankId,
                cfgType: '1'
            }
          }
        // 每次变更银行查询是否需要校验三个字段
        this.$p2svr(this.$api['_01_STM002SUPPRESS1200'], '', params)
            .then((res) => {
                if(res.payload && res.payload.length > 0) {
                    this.needVild = res.payload.find(item => item.field === 'acctNo')?.valid === '1'
                }
            })
    }
      this.getSelectList(arr)
    },
    doSearch(){
      const {transDate, bankId, acctNo, cstId}= this.queryForm

      if(bankId && ['148', '138'].includes(String(bankId))&& !acctNo && !cstId ) {
        this.$message.error('以下條件請至少輸入一項,交易主體客戶號、交易主體賬號')
        return
      }

      if(transDate && transDate.length && transDate[0] && transDate[1]) {
        this.queryForm.dateBegin = transDate[0]
        this.queryForm.dateEnd = transDate[1]
      } else {
        this.queryForm.dateBegin = ''
        this.queryForm.dateEnd = ''
      }
      delete this.queryForm.vipCodeValues;
      delete this.queryForm.employeeFlagValues;
      this.queryForm.employeeFlag = this.employeeFlagChecked?'1':'0',
      this.queryForm.vipCode = this.vipCodeChecked?'1':'0',

console.log(transDate,this.queryForm,2222);
      this.showWarning = true;
      // if(Array.isArray(this.employeeFlagArr) && this.employeeFlagArr.length > 0) {
      //   this.queryForm.employeeFlag = '1'
      // } else {
      //   this.queryForm.employeeFlag = '0'
      // }
      // if(Array.isArray(this.vipCodeArr) && this.vipCodeArr.length > 0) {
      //   this.queryForm.vipCode = '1'
      // } else {
      //   this.queryForm.vipCode = '0'
      // }
      this.$refs['0001.A129.0010'].doSearch()
    }, 
    getCusInfo(){
      const {tranCode}= this.queryForm;
      console.log('bankIdObj:', this.bankIdObj); // 调试信息：
      console.log('开始调用 getCusInfo 方法'); // 调试信息：开始调用 getCusInfo 方法
      console.log('tranCode:', tranCode); // 调试信息：输出 tranCode 的值
      if(!tranCode) {
        return
      }
      const params = {
        optCode: 'STM004GET1103',
        payload: {
          bankId:this.bankIdObj
            [this.language][0].key,
          seqNo:'',
          tranCode
        }
      };
      console.log('请求参数:', params); // 调试信息：输出请求参数
      this.$p2svr(this.$api['_01_STM004GET1100'], '', params)
        .then((res) => {
          console.log('交易码检查返回了', res);
          const { result } = res.payload ? res.payload : {};
          if (result === '0') {
            this.$message.error('交易码不存在');
          } else if (result === '1') {
            this.$message.success('交易码存在');
          }
        }).finally(() => {
        });
    },

    async doDetail(row){
      console.log(row.rows)
      this.detailRowData = row.rows?.[0] || {}
      const arr = row.rows
      if(arr.length !== 1){
        this.$message.warning(this.$t('stm.handleTips.selectOne'))
        return
      }
      console.log('arr',arr); // 调试信息
      const params = {
        optCode: 'STM004GET1102',
        payload: {
          seqNo:arr[0].seqno,
          bankId:arr[0].bankid,
          cstId:arr[0].cstid
        }
      }
      console.log('params',params); // 调试信息
      let detailsData = {}
      await this.$p2svr(this.$api['_01_STM004GET1100'] , 'RequestPoAuth', params).then(res => {
        // console.log(res)
        //return
        detailsData = res.payload || {}

      }).finally(() => {
        this.loading = false
      })
      console.log(detailsData, 'detailsData===')
      const obj = {
        columnsNum: 2,
        zhWidth: 100,
        usWidth: 150,
        columnsConfig: this.detailColumn,
        title: 'stm.cusTransHis.transDetail',
        detailsData,
      }
      this.$refs['columnDialog'].initPage(obj)
    }, 
    async doLocalClearingSysTranInfo(row){
      const arr = row.rows
      if(arr.length !== 1){
        this.$message.warning(this.$t('stm.handleTips.selectOne'))
        return
      }
      const params = {
        optCode: 'STM004GET1104',
        payload: {
          bankId:arr[0].bankid,
          tranId:arr[0].tranid,
          tranDt:arr[0].trandt
        },
      }
      let TranInfoData = {}
      await this.$p2svr(this.$api['_01_STM004GET1100'] , 'RequestPoAuth', params).then(res => {
        //console.log(res)
        TranInfoData = res.payload || {}

      }).finally(() => {
        this.loading = false
      })
      console.log(TranInfoData, 'TranInfoData===')
      const obj2 = {
        columnsNum: 2,
        zhWidth: 100,
        usWidth: 150,
        columnsConfig: this.localClearingSysTranInfoList,
        title: 'stm.cusTransHis.LocalClearingSysTranInfo',
        detailsData: TranInfoData,
      }
      this.$refs['columnDialogTwo'].initPage(obj2)
    },
    validateDoubleProp(rule, value, callback) {
        const {transDate, acctNo, cstId}= this.queryForm
        
        // 判断是否需要检验
        if(this.needVild) {
            if(rule.field === 'transDate') {
                console.log(value, 123);
                
                if((!value || !value.length || !value[0] || !value[1])&& !cstId && !acctNo) {
                 return callback(new Error(this.$t('请至少在交易日期，交易号，交易主体三个中填写一个查询参数')));
                }
            }
        } else {
            return callback(); 
        }
    } ,
    validateDoublePropA(rule, value, callback) {
        const {transDate, acctNo, cstId}= this.queryForm
        
        // 判断是否需要检验
        if(this.needVild) {
            if(rule.field === 'cstId') {
                if( !value && !acctNo && (!transDate || !transDate.length || !transDate[0] || !transDate[1])) {
                 return callback(new Error(this.$t('请至少在交易日期，交易号，交易主体三个中填写一个查询参数')));
                }
            }
        } else {
            return callback(); 
        }
    } ,
    validateDoublePropB(rule, value, callback) {
        const {transDate, acctNo, cstId}= this.queryForm
        
        // 判断是否需要检验
        if(this.needVild) {
            if(rule.field === 'acctNo') {
                if( !value && !cstId && (!transDate || !transDate.length || !transDate[0] || !transDate[1])){
                 return callback(new Error(this.$t('请至少在交易日期，交易号，交易主体三个中填写一个查询参数')));
                }
            }
        } else {
            return callback(); 
        }
    }
  }
}
</script>